<style>
</style>
<!--  -->
<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @closed="closed" :close-on-click-modal="false">
      <el-form :model="page" v-loading="loading" :rules="rules" ref="pageForm" @submit.native.prevent>
        <el-form-item label="页面名称" label-width="120px" prop="name">
          <el-input v-model="page.name" autocomplete="off" size="medium" maxlength="50" style="width:80%;"
            placeholder="输入50个字符以内的页面名称"></el-input>
        </el-form-item>
        <el-form-item label="导航中显示" label-width="120px">
          <el-switch v-model="page.status" active-color="#13ce66">
          </el-switch>
          <span
            style="line-height: 1;font-size: 14px;display: inline-block;color:#666666;">&nbsp;{{page.status?'显示':'隐藏'}}</span>
        </el-form-item>
        <el-form-item label="页面级别" label-width="120px"><!--v-if="page.id == 0"-->
          <el-select v-model="page.parentId" placeholder="选择级别" size="medium" style="width:80%;">
            <el-option label="顶级" :value="0"></el-option>
            <template v-for="pag in pageList[0]">
              <el-option style="padding-left:36px;" v-if="(page.id == 0 || page.id != pag.id) && pag.type != 2"
                :key="pag.id" :label="pag.name" :value="pag.id"></el-option>
              <template v-for="pa in pageList[pag.id]">
                <el-option style="padding-left:48px;" v-if="(page.id == 0 || page.id != pa.id) && pa.type != 2"
                  :key="pa.id" :label="' - '+pa.name" :value="pa.id"></el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="页面类型" label-width="120px">
          <el-select v-model="page.type" placeholder="请选择页面类型" size="medium" style="width:80%;">
            <el-option label="普通页" :value="1"></el-option>
            <el-option label="系统页" :value="2"></el-option>
            <el-option label="外链页" :value="3"></el-option>
            <!-- <el-option label="内链页" :value="4"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item v-loading="loadingRewrite" label="自定义链接" label-width="120px"
          v-if="page.type === 1 || page.type === 2" prop="rewrite">
          <el-input v-model="page.rewrite" autocomplete="off" size="medium" maxlength="100" style="width:80%;"
            placeholder="输入非全数字、无空格特殊符号等且100个字符以内的字符串"></el-input>
          <p style="color:#888888;">路径：/{{page.rewrite? page.rewrite: '{系统默认ID}'}}.html</p>
        </el-form-item>
        <el-form-item label="外部链接" label-width="120px" v-if="page.type === 3" prop="url">
          <el-input v-model="page.url.external" autocomplete="off" size="medium" maxlength="200" style="width:80%;"
            placeholder="输入地址"></el-input>
          <!-- <p style="color:#888888;"><span class="blue">注意：</span>链接需要带有请求协议（http、https或者//）</p> -->
        </el-form-item>
        <el-form-item label="内部链接" label-width="120px" v-if="page.type === 4" :show-message="internal">
          <el-select v-model="page.url.internal.page" placeholder="选择页面" size="medium" style="width:180px;">
          </el-select>
          <el-select v-model="page.url.internal.cate" placeholder="选择系统分类" size="medium" style="width:180px;">
          </el-select>
          <el-select v-model="page.url.internal.item" placeholder="选择系统详情" size="medium" style="width:180px;">
          </el-select>
          <p style="color:#888888;">只能选择系统当中已有的链接页面！</p>
        </el-form-item>
        <el-form-item label="挂载系统" label-width="120px" v-if="page.type === 2" prop="systemId">
          <el-select v-model="page.systemId" placeholder="选择系统" size="medium" style="width:80%;">
            <template v-for="item in systemList">
              <el-option :key="item.id" :label="item.name" :value="item.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转方式" label-width="120px">
          <el-radio v-model="page.target" label="_self">当前窗口中打开</el-radio>
          <el-radio v-model="page.target" label="_blank">新窗口中打开</el-radio>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" size="small">取 消</el-button>
        <el-button type="primary" @click="onSubmit()" :disabled="loading || loadingRewrite" size="small">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    propsOnSubmit: {
      type: Function
    }
  },
  created () {

  },
  data () {
    // 自定义校验
    var checkName = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('页面名称不能都为空格'))
      } else {
        callback()
      }
    }
    var checkRewrite = (rule, value, callback) => {
      if (parseInt(this.page.type) === 3 || parseInt(this.page.type) === 4) {
        callback()
      }
      if (value) {
        if (/^\d+$/.test(value)) {
          callback(new Error('不能全部为数字'))
          return
        }
        if (!/([\u4e00-\u9fa5]|[a-zA-Z0-9])+/.test(value)) {
          callback(new Error('带有空格或特殊符号'))
          return
        }
        if (value.length < 3) {
          callback(new Error('不能小于3个字符'))
          return
        }
        if (/\s/.test(value)) {
          callback(new Error('带有空格'))
          return
        }
        let patrn = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        if (patrn.test(value)) {
          callback(new Error('带有特殊符号'))
          return
        }
        callback()
        // this.loadingRewrite = true
        // this.$jpost('/page/valid/rewrite', { id: this.page.id, rewrite: value }).then(response => {
        //   this.loadingRewrite = false
        //   if (response && response.error) {
        //     callback(new Error(response.error))
        //     return
        //   }
        //   if (response && response.rewrite) {
        //     callback()
        //   }
        // }, () => {
        //   this.loadingRewrite = false
        // })
      } else {
        callback(new Error('不能为空'))
      }
    }

    var checkSystemId = (rule, value, callback) => {
      if (parseInt(this.page.type) === 2) {
        let systemId = parseInt(this.page.systemId)
        if (isNaN(systemId) || systemId < 1) {
          callback(new Error('请挂载系统'))
          return
        }
      } else {
        this.page.systemId = null
      }
      callback()
    }

    var checkUrl = (rule, value, callback) => {
      if (parseInt(this.page.type) === 3) {
        if (!value.external) {
          callback(new Error('请输入链接地址'))
        }
      }
      // if (value.external) {
      //   if (!/^(http|https|\/\/)/.test(value.external)) {
      //     callback(new Error('需要http、https或者//开头'))
      //   }
      // }
      callback()
    }
    return {
      dialogFormVisible: false,
      title: '',
      loading: true,
      loadingRewrite: false,
      page: {},
      rules: {
        name: [
          { required: true, message: '请输入页面名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        rewrite: [{ required: true, validator: checkRewrite, trigger: 'change' }],
        systemId: [{ required: true, validator: checkSystemId, trigger: 'blur' }],
        url: [{ required: true, validator: checkUrl, trigger: 'blur' }]
      },
      // 是否加载完成
      bool: {
        pageList: false,
        systemList: false
      },
      // 当前系统当中已有的 page 数据
      pageList: [],
      // 当前系统当中已有的 system 数据
      systemList: [],
      // 是否显示错误
      internal: true
    }
  },
  computed: {
    pageName () {
      return this.page.name
    },
    pageType () {
      return this.page.type
    }
  },
  watch: {
    pageType: {
      handler (newValue) {
        let type = parseInt(newValue)
        if (type !== 2) {
          this.page.systemId = null
        }
        if (type === 4) {
          this.internal = false
        }
        if (type === 3) {
          this.internal = true
        }
      },
      deep: true
    },
    pageName: {
      handler (newValue) {
        if (this.page.id > 0) {
          return
        }
        if (newValue) {
          let toLocaleLowerCase = this.$pinyin.getFullChars(newValue).toLocaleLowerCase()
          let rewrite = ''
          for (let i in toLocaleLowerCase) {
            let str = toLocaleLowerCase[i]
            if (/([\u4e00-\u9fa5]|[a-zA-Z0-9])/.test(str)) {
              rewrite += this.$pinyin.getFullChars(str).toLocaleLowerCase()
            }
          }
          if (rewrite.indexOf(this.page.rewrite) === 0) {
            this.page.rewrite = rewrite
          }
        } else {
          this.page.rewrite = this.page.rewrite
        }
      },
      deep: true
    },
    bool: {
      handler (newValue) {
        if (newValue.pageList && newValue.systemList) {
          this.loading = false
        } else {
          this.loading = true
        }
      },
      deep: true
    }
  },
  methods: {
    onSubmit () {
      if (this.loading) {
        return
      }
      this.$refs['pageForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          let page = JSON.parse(JSON.stringify(this.page))
          // 如果系统id为空则改成为0
          if (page.systemId == null) {
            page.systemId = 0
          }
          // status 改成 0 1的方式
          page.status = page.status ? 1 : 0
          // url 确认
          let url = page && page.url ? page.url : {
            type: 0,
            external: '',
            internal: {}
          }
          if (!url.type) {
            url.type = 0
          }
          if (this.pageType === 3) {
            url.type = 1
            page.rewrite = null
          } else if (this.pageType === 4) {
            url.type = 2
            page.rewrite = null
          }
          page.url = JSON.stringify(url)
          // 请求写入数据库
          this.$jpost('/page/save', page).then(response => {
            this.loading = false
            if (response && response.id) {
              this.propsOnSubmit(page)
              this.cancel()
            }
          })
        } else {
          return false
        }
        if (this.$refs['pageForm']) {
          this.$refs['pageForm'].clearValidate()
        }
      })
    },
    show (page, title) {
      if (title) {
        this.title = title
      }
      // 打开窗口
      this.dialogFormVisible = true
      // 加载 loading
      let bool = this.bool
      bool.systemList = false
      bool.pageList = false
      this.bool = JSON.parse(JSON.stringify(bool))
      // 获取页面数据
      this.$post('/page/infos').then(response => {
        if (response && response.pages) {
          this.pageList = response.pages
        }
        let bool = this.bool
        bool.pageList = true
        this.bool = JSON.parse(JSON.stringify(bool))
      }, (error) => {
        console.error(error)
        let bool = this.bool
        bool.pageList = true
        this.bool = JSON.parse(JSON.stringify(bool))
      })
      // 获取系统数据
      this.$post('/system/infos').then(response => {
        if (response && response.length > 0) {
          this.systemList = response
        }
        let bool = this.bool
        bool.systemList = true
        this.bool = JSON.parse(JSON.stringify(bool))
      }, (error) => {
        console.error(error)
        let bool = this.bool
        bool.systemList = true
        this.bool = JSON.parse(JSON.stringify(bool))
      })
      this.$nextTick(() => {
        if (page) {
          if (this.$refs['pageForm']) {
            // this.$refs['pageForm'].resetFields()
            this.$refs['pageForm'].clearValidate()
          }
          this.page = initPageData(page)
        } else {
          if (this.$refs['pageForm']) {
            this.$refs['pageForm'].clearValidate()
          }
          this.page = nullData()
        }
      })
    },
    cancel () {
      if (this.$refs['pageForm']) {
        this.$refs['pageForm'].clearValidate()
      }
      this.dialogFormVisible = false
    },
    hidden () {
    },
    closed () {
      this.page = nullData()
      if (this.$refs['pageForm']) {
        this.$refs['pageForm'].clearValidate()
      }
      this.dialogFormVisible = false
    }
  }
}

function initPageData (data) {
  let jurl = null
  try {
    jurl = JSON.parse(data.url)
  } catch (error) {
    jurl = {
      type: 0,
      external: '',
      internal: {}
    }
  }
  return {
    id: data.id,
    name: data.name,
    status: data.status > 0,
    parentId: data.parentId,
    systemId: data.systemId > 0 ? data.systemId : null,
    type: data.type,
    rewrite: data.rewrite,
    target: data.target,
    url: jurl
  }
}

function nullData () {
  return {
    id: 0,
    name: '',
    status: true,
    parentId: 0,
    systemId: null,
    type: 1,
    rewrite: '',
    target: '_self',
    url: {
      type: 0,
      external: '',
      internal: {}
    }
  }
}

</script>
